// pages/airport/pickup.js
var airportTerminals = [];
var amapFile = require('../../libs/amap-wx.js');
var config = require('../../config.js');
var util = require('../../network_util.js');
var commonjs = require('../../common.js');
var base = require('../../base.js');
var fromInfo = {};
var app = getApp();

//比较函数，根据经纬度距离判断乘客所在机场
var compare = function (prop) {
  return function (obj1, obj2) {
    var val1 = obj1[prop];
    var val2 = obj2[prop];
    if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
      val1 = Number(val1);
      val2 = Number(val2);
    }
    if (val1 < val2) {
      return -1;
    } else if (val1 > val2) {
      return 1;
    } else {
      return 0;
    }
  }
}

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // avatar: "../../images/avatar-d.png",
    placeState: 0, //可下单状态， 0-没达到下单条件， 1-可下单了
    airportTerminals: [],
    index: 0,
    destination: "您在哪下车",
    price: 100,
    fee: 0,
    localLat: "",
    localLng: "",
    destinationLL: "", //经纬度
    fromInfo:{}, //出发地信息 cityId, cityName, airportName, terminal, position
    destinationCityName: "",
    display: "none",
    orderId: "",
    userInfo: {},
    wxUserInfo: "",
    // locationInfo: {},
    // localCityName: "",
    showModalStatus: false,
    tripParams: { type: 1, carType: 1 }, //type=1 立即用车， carType=1 第一种车型
    customTelephone: "073184867966", //公司客服电话
    priceMode: 1, //1-套餐， 2-普通，3-一口价
    multiArray: [['长沙市', '贵阳市', '武汉市'], ['黄花国际机场T1航站楼', '黄花国际机场T2航站楼']],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("onLoad...");
    //1. 初始化数据，可能从缓存取，缓存没有的话从定位取
    this.initFrom(); //定位、获取城市ID、获取航站楼、获取当前航站楼
    //2.然后调高德接口规划行驶路线并预估价格
    this.getDrivingRoute();
  },

  /**
    * 生命周期函数--监听页面显示
  */
  onShow: function () {
    // console.log("onShow...");
    // //1. 初始化数据，可能从缓存取，缓存没有的话从定位取
    // this.initFrom(); //定位、获取城市ID、获取航站楼、获取当前航站楼
    // //2.然后调高德接口规划行驶路线并预估价格
    // this.getDrivingRoute();

    // console.log(app.globalData);
    // this.setData({ wxUserInfo: app.globalData.wxUserInfo });
    if (!commonjs.isEmpty(wx.getStorageSync("wxUserInfo"))) {
      this.setData({ wxUserInfo: wx.getStorageSync("wxUserInfo") });
    }else{
      this.setData({ wxUserInfo: app.globalData.wxUserInfo });
    }
    console.log(this.data.wxUserInfo);
  },
  initFrom: function () {
    var that = this;
    this.setData({ userInfo: wx.getStorageSync("userInfo") });
    // this.setData({ userInfo: app.globalData.userInfo });
    
    // if(!commonjs.isEmpty(this.data.fromInfo.position)){
    //   console.log("init.fromInfo not empty: ");
    //   console.log(this.data.fromInfo);
    // } else {
      if (!commonjs.isFromInfoEmpty(app.globalData.fromInfo)) {
        console.log("init.fromInfo is empty, get from app.globalData.");
        this.setData({ fromInfo: app.globalData.fromInfo})
      }
      else{
        console.log("init.fromInfo is empty, get from API.");
      //1.首先定位当前城市
      var key = config.aMapKey;
      var myAmapFun = new amapFile.AMapWX({ key: key });
      var cityName = "";
      console.log("1.首先定位当前城市:");
      // var localCityName = wx.getStorageSync("localCityName");
        wx.showLoading({ title: "定位中...", mask: true });
        myAmapFun.getRegeo({
          iconPath: "../../images/marker.png", iconWidth: 22, iconHeight: 32,
          success: function (data) {
            wx.hideLoading();
            console.log("getRegeo.data: ");
            console.log(data);
            cityName = data[0].regeocodeData.addressComponent.city;
            that.setData({ localLat: data[0].latitude });
            that.setData({ localLng: data[0].longitude });
            fromInfo.cityName = cityName;
            that.setData({ fromInfo: fromInfo });
            // that.setData({ fromCityName: cityName });
            //3. 获取城市ID
            that.getCityId();
          },
          fail: function (info) {
            // wx.showModal({title:info.errMsg})
            wx.hideLoading();
            wx.showToast({
              title: '定位失败，请检查您的网络设置。',
            })
            console.log(info);
          },
          complete: function (ff) {
            console.log(ff);
          }
        })
    }
    // }
  },
  getCityId: function () {
      var that = this;
      //2.获取城市列表
      util._get(config.fromCityList,
        function (res) {
          // console.log("pickup.getCityId.02: get cityList from api success: ");
          // console.log(res);
          var found = false;
          fromInfo = that.data.fromInfo;
          for (var i = 0; i < res.data.data.length; i++) {
            if (fromInfo.cityName.replace("市", "") 
                == res.data.data[i].cityName.replace("市", "")) {
              fromInfo.cityId = res.data.data[i].id;
              that.setData({ fromInfo: fromInfo });
              //4. 获取地区（航站楼列表）
              console.log("get cityId from api, that.data.fromInfo: ");
              console.log(that.data.fromInfo);
              app.globalData.fromInfo = that.data.fromInfo;
              // console.log("app.globalData.latestFromInfo:")
              // console.log(app.globalData.latestFromInfo);
              that.getTerminalList(that.data.fromInfo.cityId);
              found = true;
              break;
            }
          }
          if (!found) {
            wx.showToast({
              title: '当前城市未开通服务',
            })
          }
        }, function (res) {
          console.log("fromCityList fail");
          // console.log(res);
        })
  },
  getTerminalList: function (cityId) {
      var that = this;
      util._get(config.searchAddress + "?cityId=" + cityId,
        function (res) {
          // console.log(res);
          if (res.statusCode == 200) {
            if (res.data.code == 200) {
              var currentAirport = {};
              var airportTerminals = [];
              var airports = res.data.data;
              if (airports.length>1){ //如果机场数>0，将离乘客最近的置为乘客的出发地
              //先计算距离
                  airports.forEach(function (item, index, input){ 
                  input[index].distance = commonjs.getDisance(
                    that.data.localLat,
                    that.data.localLng,
                    item.position.split(',')[1],
                    item.position.split(',')[0]
                  );
                })
                airports.sort(compare("distance"));
                console.log("sorted airports: ");
                console.log(airports);
              }else{
                // currentAirport = 
              }
              currentAirport = airports[0];
              var terminals = commonjs.trim(currentAirport.terminalBuilding, ',').split(',');
              var fromInfo = that.data.fromInfo;
                  // fromInfo.cityId = cityId;
              // fromInfo.cityName = that.data.fromCityName;
                  fromInfo.airportId = currentAirport.id;
                  fromInfo.airportName = currentAirport.airportName;
                  fromInfo.terminal = currentAirport.airportName + terminals[0];
                  fromInfo.position = currentAirport.position;
                that.setData({ fromInfo: fromInfo})
            } else {
              wx.showToast({
                title: res.data.msg + '(' + res.data.code + ')',
              })
            }
          } else {
            wx.showToast({
              title: '获取机场航站楼 系统错误：' + res.statusCode,
            })
          }
        })
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selectDestination: function () {
    //先判断是否已经登录
    console.log(app.globalData.userInfo);
    if (this.data.userInfo == null || this.data.userInfo == "") {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    } else {
      wx.navigateTo({
        url: 'address',
      })
    }
  },
  // onPickerChange: function (e) { //航站楼选择事件
  //   this.setData({ index: e.detail.value });
  //   //重新计算坐标
  //   this.getOriginLongNLang();
  //   //调高德接口获取行驶路线
  //   this.getDrivingRoute();
  // },
  onLimousineTap: function (e) {
    wx.showToast({ title: "该车型暂未开通，敬请期待" });
  },
  onBusiness7Tap: function (e) {
    wx.showToast({ title: "该车型暂未开通，敬请期待" });
  },
  getDrivingRoute: function () {
    console.log("3.调用高德地图接口，获取行驶路线"); 
    if (this.data.destination != '您在哪下车'
      && this.data.destination != '') {
    //先判断是否所有参数齐全，不齐的话不用调高德
    if (this.data.destinationLL == "" || commonjs.isEmpty(this.data.fromInfo.position)) {
      console.log("调高德获取行驶路线：参数不全，return")
      return;
    }
    // wx.showToast({
    //   title: "预估价加载中...",
    //   icon: "loading"
    // })
    console.log("this.data.destination: " + this.data.destination);
    wx.showLoading({ title: "预估价加载中...", mask: true });
    var that = this;
    var key = config.aMapKey;
    var myAmapFun = new amapFile.AMapWX({ key: key });
    var routeParams = {
      origin: that.data.fromInfo.position,
      destination: that.data.destinationLL,
      success: function (routeData) {
        console.log("getDrivingRoute.routeData: ");
        console.log(routeData);
        var isOut = 0;// 默认不出城
        var outMile = 0;
        console.log("cityName compare: " + that.data.fromInfo.cityName.replace("市", "") + " | " + that.data.destinationCityName.replace("市", ""))
        if (that.data.fromInfo.cityName.replace("市", "") != that.data.destinationCityName.replace("市", "")) {
          isOut = 1;
          outMile = routeData.paths[0].distance / 1000;
        }
        //计算预估价 - 设置参数
        that.setData({
          tripParams: {
            mileage: routeData.paths[0].distance / 1000, //公里
            time: (routeData.paths[0].duration / 60).toFixed(0), //分钟
            isOut: isOut,
            outMile: outMile,
            cityId: that.data.fromInfo.cityId,
            type: 1,
            carType: 1
          }
        });
        //计算预估价 - 调用
        that.caculatePrice();

      }, fail: function (routeInfo) {
        console.log(routeInfo);
      }, complete: function () {
        wx.hideToast();
        console.log("getDrivingRoute complete.");
      }
    }
    console.log("begin call getDrivingRoute")
    myAmapFun.getDrivingRoute(routeParams);
      }
  },
  caculatePrice: function () { //计算预估价
    console.log("begin call caculatePrice: ")
    var that = this;
    that.setData({ placeState: 0 });
    var upTime = escape(commonjs.dateTime(new Date().getTime()));
    // upTime = escape("2017-10-19 11:11:11");
    util._get(
      config.caculatePrice
      + "?userId=" + that.data.userInfo.id
      + "&mileage=" + that.data.tripParams.mileage
      + "&time=" + that.data.tripParams.time
      + "&isOut=" + that.data.tripParams.isOut
      + "&outMile=" + that.data.tripParams.outMile
      + "&cityId=" + that.data.fromInfo.cityId
      + "&type=" + that.data.tripParams.type
      + "&carType=" + that.data.tripParams.carType
      // + "&upTime=" + upTime
      ,
      function (res) {
        // console.log("预估价计算完成");
        wx.hideLoading();
       console.log(res,"----------------------");
        if (res.statusCode == 200) { 
          // console.log(res.data.code);
          if (res.data.code == 200) {
            // that.setData({ price: (res.data.data.price / 100).toFixed(2) });
            that.setData({ price: (res.data.data.price).toFixed(2) });
            that.setData({ fee: res.data.data.fee });
            that.setData({ orderId: res.data.data.orderId });
            that.setData({ priceMode: res.data.data.type });
            // that.setData({ btnOpacity: 1 });
            that.setData({ placeState: 1 });
            that.setData({ display: "block" });
            if (that.data.tripParams.mileage > 500) {
              that.setData({ placeState: 0 });
              wx.showModal({
                title: '行程超过500公里',
                // content: '您的行程超过了500公里，如需用车请拨打客服电话' + that.data.customTelephone,
                content: '抱歉，目前只允许500公里以内的行程。',
                confirmText: '拨打',
                cancelText: '取消',
                success: function (res) {
                  if (res.confirm) {
                    console.log("user tap confirm");
                    //调用拨打电话
                    wx.makePhoneCall({
                      phoneNumber: that.data.customTelephone,
                    })
                  } else if (res.cancel) {
                    console.log("user tap cancel");
                  }
                }
              })
            }
          } else if (res.data.code == 1025) {
            console.log(res.data.msg);
            that.setData({ display: "none" });
            wx.showToast({
              title: "系统配置错误"
            })
          } else {
            console.log(res.data.msg);
            that.setData({ display: "none" });
            wx.showToast({
              title: '预估价接口错误(' + res.data.code + ')',
            })
          }
        } else {
          wx.showToast({
            title: '预估价接口调用失败(' + res.statusCode + ')',
          })
          // console.log("调用接口失败(" + res.statusCode + ")");
          // console.log(res);
        }
        // wx.hideToast();
      },function(){
        console.log("caculate price api fail")
      }), function () {
        console.log("caculate price call api fail.")
      }
  },
  submit: function () { //下单
    //检查
    var that = this;
    console.log("开始下单：this.data.destination= " + this.data.destination)
    that.setData({ placeState: 0 }); //禁用下单按钮
    wx.showToast({
      title: '订单提交中...',
      icon: "loading"
    })
    //下单接口
    util._post_json(
      config.immediatelyOrder,
      {
        orderChannel: 1, 
        orderId: this.data.orderId,
        uId: this.data.userInfo.id,
        departureLocation: this.data.fromInfo.terminal,
        arrivedLocation: this.data.destination,
        name: this.data.userInfo.name,
        telephone: this.data.userInfo.telephone,
        isSend: 0,
        carType: 1,
        estimatePrice: this.data.price ,
        cityId: this.data.fromInfo.cityId,
        airId: this.data.fromInfo.airportId,
        departurePosition: this.data.fromInfo.position,
        arrivedPosition: this.data.destinationLL,
        airport: this.data.fromInfo.airportName,
        onTime: new Date().format('yyyy-MM-dd h:m:s'),
        arriedTime: new Date().format('yyyy-MM-dd h:m:s'), //"2017-08-23 16:40:24"
      },
      function (res) {
        // wx.hideToast();
        // console.log(res);
        if (res.statusCode == 200) { //网络正常
          if (res.data.code == 200) {
            wx.removeStorageSync("orderInfoTmp");
            //下单成功，跳转到订单页
            var currentOrder = {
              orderId: that.data.orderId,
              markers: [{
                iconPath: "../../images/icon_star@2x.png",
                id: 0,
                longitude: that.data.fromInfo.position.split(',')[0],
                latitude: that.data.fromInfo.position.split(',')[1],
                width: 20,
                height: 30
              }, {
                iconPath: "../../images/icon_end@2x.png",
                id: 1,
                longitude: that.data.destinationLL.split(',')[0],
                latitude: that.data.destinationLL.split(',')[1],
                width: 20,
                height: 30
              }]
            };
            var oit = new Array();
            if (wx.getStorageSync("orderInfoTmp") != "") {
              oit = JSON.parse(wx.getStorageSync("orderInfoTmp"));
            }
            oit.unshift(currentOrder);
            wx.setStorageSync("orderInfoTmp", JSON.stringify(oit));
            console.log("begin redirectTo order");
            // wx.redirectTo({
            //   url: 'order?orderId=' + that.data.orderId,
            // })
            wx.navigateTo({
              url: 'order?orderId=' + that.data.orderId,
            })
          } else if (res.data.code == 1001) { //
            wx.showModal({
              title: '上车地点不能为空',
              content: '',
              confirmText: "查看订单",
              cancelText: "我知道了"
            })
          } else if (res.data.code == 1002) { //
            wx.showModal({
              title: '下车地点不能为空',
              content: '',
              confirmText: "查看订单",
              cancelText: "我知道了"
            })
          } else if (res.data.code == 1003) { //
            wx.showModal({
              title: '用户ID不能为空',
              content: '',
              confirmText: "查看订单",
              cancelText: "我知道了"
            })
          } else if (res.data.code == 1005) { //有未完成的订单
            wx.showModal({
              title: '您有未完成的订单',
              content: '',
              confirmText: "查看订单",
              cancelText: "我知道了",
              success: function (res) {
                if (res.confirm) {
                  console.log("you tap confirm");
                  wx.navigateTo({
                    url: '/pages/mine/trips',
                  })
                } else if (res.cancel) {
                  console.log("you tap cancel");
                }
              }
            })
          } else if (res.data.code == 1006) { //有未完成的订单
            wx.showModal({
              title: '您有一个未支付的订单',
              content: '',
              confirmText: "查看订单",
              cancelText: "我知道了",
              success: function (res) {
                if (res.confirm) {
                  console.log("you tap confirm");
                  wx.navigateTo({
                    url: '/pages/mine/trips',
                  })
                } else if (res.cancel) {
                  console.log("you tap cancel");
                }
              }
            })
          } else if (res.data.code == 1008) { //
            wx.showModal({
              title: '下单失败',
              content: '',
            })
            that.setData({ placeState: 1 }); //启用下单按钮
          } else if (res.data.code == 1020) { //
            wx.showModal({
              title: '当前没有可服务的车辆',
              content: '',
            })
            that.setData({ placeState: 1 }); //启用下单按钮
          } else {
            wx.showModal({
              title: '接口错误(' + res.data.code + ')',
              content: '',
            })
            that.setData({ placeState: 1 }); //启用下单按钮
          }
        } else {
          wx.showToast({
            title: '网络异常(' + res.statusCode + ')',
          })
        }
      },
      function (res) {
        console.log("failllllll");
      },
      function (res) { //complete
        that.setData({ placeState: 1 }); //启用下单按钮
      }
    )
  },
  powerDrawer: function (e) {
    //判断是否已登录
    console.log(this.data.userInfo);
    console.log(this.data.wxUserInfo);
    if (!commonjs.isEmpty(this.data.userInfo)) {
      var currentStatu = e.currentTarget.dataset.statu;
      this.util(currentStatu)
    } else {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200, //动画时长
      timingFunction: "linear", //线性
      delay: 0 //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是240px)，停
    animation.translateX(-240).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateX(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })

      // console.log("currentStatu2=" + currentStatu);
      //关闭抽屉
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
        // console.log("showModalStatus2=" + this.data.showModalStatus);
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
      // console.log("showModalStatus3=" + this.data.showModalStatus);
    }
  },
  onLogout: function (e) {
    wx.showModal({
      title: '退出登录',
      content: '确定退出账号 ' + this.data.userInfo.name + ' 吗？',
      confirmText: "确定",
      cancelText: "取消",
      success: function (res) {
        if (res.confirm) {
          console.log("user tap confirm");
          wx.removeStorageSync("userInfo");
          app.globalData.userInfo = "";
          wx.redirectTo({
            url: 'pickup',
          })
        } else if (res.cancel) {
          console.log("user tap cancel");
        }
      }
    })
  },
  go2AddressFrom: function (e) {
    wx.navigateTo({
      url: 'address-from',
    })
  },
  // go2Login: function (e) {
  //   wx.redirectTo({
  //     url: '../login/login',
  //   })
  // },
  changeTerminal: function (e) {

  },
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    var data = {
      multiArray: this.data.multiArray,
      multiIndex: this.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = ['黄花国际机场T1航站楼', '黄花国际机场T2航站楼'];
            break;
          case 1:
            data.multiArray[1] = ['龙洞堡国际机场T1航站楼', '龙洞堡国际机场T2航站楼',];
            break;
          case 2:
            data.multiArray[1] = ['天河国际机场T3航站楼',];
            break;
        }
        data.multiIndex[1] = 0;
        break;

    }
    this.setData(data);
  },
  clearCache: function () {
    wx.getStorageInfo({
      success: function (res) {
        console.log(res);
        res.keys.forEach(function (key) {
          if (key != "userInfo" && key != "wxUserInfo"
            && key != "systemInfo" && key != "openId") {
            wx.removeStorage({
              key: key,
              success: function (res) { },
            })
          }
        })
      },
    })
    // wx.clearStorage();
    // wx.clearStorageSync();
    wx.showToast({
      title: '缓存已清理',
    })
  }
})

Date.prototype.format = function (format) {
  var date = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S+": this.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1
        ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}